/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.noraxidium.util;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * Basically an adapter between byte buffers and streams. Necessary for library code,
 * if we want to maintain shifting of chunks of bytes around.
 *
 * @author deus
 * @version 1.0
 * @since Jul 6, 2010 3:03:09 PM
 */
public class ByteBufferBackedInputStream extends InputStream {
  private static final Logger LOGGER = Logger.getLogger(ByteBufferBackedInputStream.class);
  private ByteBuffer buf;

  public ByteBufferBackedInputStream(ByteBuffer buf) {
    this.buf = buf;
  }

  @Override public synchronized int read() throws IOException {
    if (!buf.hasRemaining()) {
      return -1;
    }
    return buf.get();
  }

  @Override public synchronized int read(byte[] bytes, int off, int len) throws IOException {
    len = Math.min(len, buf.remaining());
    buf.get(bytes, off, len);
    return len;
  }
}
